package com.king.pattem.threadpool;

/**
 * @author taomk
 * @version 1.0
 * @since 15-2-5 下午10:01
 */
public class PThread extends Thread {

	// 线程池
	private ThreadPool pool;

	// 任务
	private Runnable target;

	private boolean isShutDown = false;

	private boolean isIdle = false;

	// 构造函数
	public PThread(Runnable target, String name, ThreadPool pool) {
		super(name);
		this.pool = pool;
		this.target = target;
	}

	public Runnable getTarget() {
		return target;
	}

	public boolean isIdle() {
		return isIdle;
	}

	@Override
	public void run() {

		try {
			// 只要没有关闭，则一只不结束该线程
			while (!isShutDown) {
				isIdle = false;
				if (target != null) {
					// 运行任务
					target.run();
				}
				// 任务结束了，到闲置状态
				isIdle = true;
				// 该任务结束后，不关闭线程，而是放入线程池空闲队列
				pool.repool(this);
				synchronized (this) {
					// 线程空闲，等待新的任务到来
					wait();
				}

				isIdle = false;
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public synchronized void setTarget(Runnable target) {
		this.target = target;

		// 设置了任务之后，通知run方法，开始执行这个任务
		notifyAll();
	}

	public synchronized void shutDown() {
		isShutDown = true;
		notifyAll();
	}

}
